// collection.js
const app = getApp()
const collectionUtil = require('../../utils/collectionUtil.js')

Page({
  data: {
    allCollections: [], // 存储所有收藏数据
    filteredCollections: [], // 当前显示的收藏数据
    currentTab: 0,
    tabs: [
      { id: 0, name: '全部', count: 0 },
      { id: 1, name: '课程', count: 0 },
      { id: 2, name: '穴位', count: 0 },
      { id: 3, name: '商品', count: 0 }
    ],
    loading: false,
    userInfo: {
      isLogin: false
    }
  },

  onLoad() {
    this.loadUserInfo()
    this.loadCollections()
  },

  onShow() {
    this.loadCollections()
    // 通知用户页面更新统计数据
    this.notifyUserPageUpdate()
  },

  // 加载用户信息
  loadUserInfo() {
    const globalUserInfo = app.getUserInfo()
    if (globalUserInfo && globalUserInfo.isLogin) {
      this.setData({ userInfo: globalUserInfo })
    } else {
      this.setData({ 
        userInfo: {
          isLogin: false
        }
      })
    }
  },

  // 加载收藏数据
  loadCollections() {
    if (!this.data.userInfo.isLogin) {
      this.setData({ 
        allCollections: [],
        filteredCollections: [],
        tabs: this.data.tabs.map(tab => ({ ...tab, count: 0 }))
      })
      return
    }

    this.setData({ loading: true })
    this.getCollectionsFromAPI()
  },

  // 从API获取收藏数据
  async getCollectionsFromAPI() {
    // 获取用户ID，支持多种字段格式
    const userInfo = this.data.userInfo
    const userId = userInfo.userId || userInfo.id
    
    if (!userId) {
      console.error('用户ID不存在，无法获取收藏数据')
      this.setData({ 
        loading: false,
        allCollections: [],
        filteredCollections: [],
        tabs: this.data.tabs.map(tab => ({ ...tab, count: 0 }))
      })
      return
    }
    
    try {
      const result = await collectionUtil.getCollections(userId)
      this.setData({ loading: false })
      
      if (result.success && result.data) {
        const collections = result.data.map(item => {
          let collectionData = {
            id: item.id,
            entityId: item.entityId,
            entityType: item.entityType,
            type: item.entityType, // 用于显示
            title: '未知标题',
            description: '',
            cover: this.getDefaultCover(item.entityType),
            price: 0,
            createTime: item.collectTime ? this.formatDate(item.collectTime) : ''
          }
          
          // 根据实体类型设置不同的数据
          if (item.entityType === 'product' && item.product) {
            collectionData.title = item.product.name || '商品'
            collectionData.description = item.product.intro || ''
            collectionData.cover = item.product.cover || this.getDefaultCover('product')
            collectionData.price = item.product.price || 0
          } else if (item.entityType === 'content' && item.content) {
            collectionData.title = item.content.title || '课程'
            collectionData.description = item.content.intro || ''
            collectionData.cover = item.content.cover || this.getDefaultCover('course')
            collectionData.price = item.content.price || 0
            // 将content类型映射为course用于显示
            collectionData.type = 'course'
          }
          
          return collectionData
        })
        
        // 统计各类型数量
        const tabs = this.data.tabs.map(tab => {
          let count = 0
          switch(tab.id) {
            case 0: // 全部
              count = collections.length
              break
            case 1: // 课程
              count = collections.filter(item => item.type === 'course').length
              break
            case 2: // 穴位
              count = collections.filter(item => item.type === 'acupoint').length
              break
            case 3: // 商品
              count = collections.filter(item => item.type === 'product').length
              break
          }
          return { ...tab, count }
        })
        
        this.setData({
          allCollections: collections,
          tabs: tabs
        })
        
        // 初始筛选
        this.filterCollections(this.data.currentTab)
      } else {
        this.setData({
          allCollections: [],
          filteredCollections: [],
          tabs: this.data.tabs.map(tab => ({ ...tab, count: 0 }))
        })
      }
    } catch (error) {
      console.error('获取收藏数据失败:', error)
      this.setData({ 
        loading: false,
        allCollections: [],
        filteredCollections: [],
        tabs: this.data.tabs.map(tab => ({ ...tab, count: 0 }))
      })
    }
  },

  // 切换标签
  onTabChange(e) {
    const tabId = e.currentTarget.dataset.id
    this.setData({ currentTab: tabId })
    this.filterCollections(tabId)
  },

  // 筛选收藏
  filterCollections(tabId) {
    let filteredCollections = []
    
    switch(tabId) {
      case 0: // 全部
        filteredCollections = this.data.allCollections
        break
      case 1: // 课程
        filteredCollections = this.data.allCollections.filter(item => item.type === 'course')
        break
      case 2: // 穴位
        filteredCollections = this.data.allCollections.filter(item => item.type === 'acupoint')
        break
      case 3: // 商品
        filteredCollections = this.data.allCollections.filter(item => item.type === 'product')
        break
    }
    
    this.setData({ filteredCollections })
  },

  // 收藏项点击
  onCollectionTap(e) {
    const item = e.currentTarget.dataset.item
    if (!item) return
    
    // 根据类型跳转到不同页面
    let url = ''
    switch(item.type) {
      case 'course':
        url = `/pages/course-detail/course-detail?id=${item.entityId}`
        break
      case 'acupoint':
        url = `/pages/acupoint-detail/acupoint-detail?id=${item.entityId}`
        break
      case 'product':
        url = `/pages/mall/mall`
        break
      default:
        return
    }
    
    if (url) {
      wx.navigateTo({ url })
    }
  },

  // 删除收藏
  onRemoveCollection(e) {
    const item = e.currentTarget.dataset.item
    if (!item) return
    
    wx.showModal({
      title: '确认删除',
      content: `确定要删除"${item.title}"吗？`,
      success: (res) => {
        if (res.confirm) {
          this.removeCollectionFromAPI(item)
        }
      }
    })
  },

  // 从API删除收藏
  async removeCollectionFromAPI(item) {
    const userInfo = this.data.userInfo
    const userId = userInfo.userId || userInfo.id
    
    if (!userId) {
      console.error('用户ID不存在，无法删除收藏')
      wx.showToast({
        title: '用户信息错误',
        icon: 'none'
      })
      return
    }
    
    try {
      const result = await collectionUtil.removeCollection(userId, item.entityType, item.entityId)
      if (result.success) {
        // 从本地数据中移除
        const allCollections = this.data.allCollections.filter(collection => 
          !(collection.entityId === item.entityId && collection.entityType === item.entityType)
        )
        
        // 重新统计数量
        const tabs = this.data.tabs.map(tab => {
          let count = 0
          switch(tab.id) {
            case 0: // 全部
              count = allCollections.length
              break
            case 1: // 课程
              count = allCollections.filter(item => item.type === 'course').length
              break
            case 2: // 穴位
              count = allCollections.filter(item => item.type === 'acupoint').length
              break
            case 3: // 商品
              count = allCollections.filter(item => item.type === 'product').length
              break
          }
          return { ...tab, count }
        })
        
        this.setData({
          allCollections: allCollections,
          tabs: tabs
        })
        
        // 重新筛选
        this.filterCollections(this.data.currentTab)
        
        collectionUtil.showResult(result, '删除成功')
      } else {
        collectionUtil.showResult(result, '删除成功', '删除失败')
      }
    } catch (error) {
      console.error('删除收藏失败:', error)
      collectionUtil.showResult(error, '删除成功', '删除失败')
    }
  },

  // 批量删除
  onBatchDelete() {
    const currentTab = this.data.currentTab
    let itemsToDelete = []
    
    if (currentTab === 0) {
      itemsToDelete = this.data.allCollections
    } else {
      const typeMap = { 1: 'course', 2: 'acupoint', 3: 'product' }
      itemsToDelete = this.data.allCollections.filter(item => item.type === typeMap[currentTab])
    }
    
    if (itemsToDelete.length === 0) {
      wx.showToast({
        title: '没有可删除的收藏',
        icon: 'none'
      })
      return
    }
    
    wx.showModal({
      title: '批量删除',
      content: `确定要删除${itemsToDelete.length}个收藏吗？`,
      success: (res) => {
        if (res.confirm) {
          this.batchDeleteCollections()
        }
      }
    })
  },

  // 批量删除收藏
  async batchDeleteCollections() {
    const currentTab = this.data.currentTab
    let itemsToDelete = []
    
    if (currentTab === 0) {
      itemsToDelete = this.data.allCollections
    } else {
      const typeMap = { 1: 'course', 2: 'acupoint', 3: 'product' }
      itemsToDelete = this.data.allCollections.filter(item => item.type === typeMap[currentTab])
    }
    
    if (itemsToDelete.length === 0) {
      wx.showToast({
        title: '没有可删除的收藏',
        icon: 'none'
      })
      return
    }
    
    const userInfo = this.data.userInfo
    const userId = userInfo.userId || userInfo.id
    
    if (!userId) {
      console.error('用户ID不存在，无法批量删除收藏')
      wx.showToast({
        title: '用户信息错误',
        icon: 'none'
      })
      return
    }
    
    wx.showLoading({
      title: '删除中...'
    })
    
    const items = itemsToDelete.map(item => ({
      userId: userId,
      entityId: item.entityId,
      entityType: item.entityType
    }))
    
    try {
      const result = await collectionUtil.batchRemoveCollections(items)
      wx.hideLoading()
      
      collectionUtil.showResult(result, result.message || '批量删除成功')
      
      // 重新加载数据
      this.loadCollections()
    } catch (error) {
      wx.hideLoading()
      console.error('批量删除收藏失败:', error)
      collectionUtil.showResult(error, '批量删除成功', '批量删除失败')
    }
  },

  // 搜索输入
  onSearchInput(e) {
    const keyword = e.detail.value.toLowerCase()
    if (!keyword) {
      this.filterCollections(this.data.currentTab)
      return
    }
    
    const filteredCollections = this.data.allCollections.filter(item => 
      item.title.toLowerCase().includes(keyword) || 
      item.description.toLowerCase().includes(keyword)
    )
    
    this.setData({ filteredCollections })
  },

  // 去发现页面
  goToDiscover() {
    wx.switchTab({
      url: '/pages/index/index'
    })
  },

  // 获取默认封面
  getDefaultCover(type) {
    const defaultCovers = {
      'course': '/images/courses/course1.svg',
      'acupoint': '/images/acupoints/acupoint1.svg',
      'product': '/images/products/product1.svg'
    }
    return defaultCovers[type] || '/images/logo.png'
  },

  // 图片加载错误
  onImageError(e) {
    const index = e.currentTarget.dataset.index
    const filteredCollections = this.data.filteredCollections
    const allCollections = this.data.allCollections
    
    const item = filteredCollections[index]
    const defaultImage = item ? this.getDefaultCover(item.type) : '/images/logo.png'
    
    if (filteredCollections[index]) {
      filteredCollections[index].cover = defaultImage
    }
    
    const itemId = filteredCollections[index]?.id
    if (itemId) {
      const allIndex = allCollections.findIndex(item => item.id === itemId)
      if (allIndex !== -1) {
        allCollections[allIndex].cover = defaultImage
      }
    }
    
    this.setData({
      filteredCollections: filteredCollections,
      allCollections: allCollections
    })
  },

  // 去登录
  goToLogin() {
    wx.navigateTo({
      url: '/pages/login/login'
    })
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadCollections()
    wx.stopPullDownRefresh()
  },

  // 通知用户页面更新统计数据
  notifyUserPageUpdate() {
    // 通过事件总线通知用户页面更新统计数据
    const pages = getCurrentPages()
    const userPage = pages.find(page => page.route === 'pages/user/user')
    if (userPage && userPage.refreshStats) {
      userPage.refreshStats()
    }
  },

  // 格式化日期
  formatDate(dateString) {
    if (!dateString) return ''
    const date = new Date(dateString)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    return `${year}-${month}-${day}`
  }
})